<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="/css/bootstrap.min.css">

</head>

<body>
    <input type="file" name="" id="file"><button type="submit" id="submit">上传文件</button>
    <br>
    <div class="progress" style="width: 500px; margin: 15px 10px;">
        <div class="progress-bar progress-bar-striped active" style="width: 0" id="jdt">
            <span class="sr-only"> </span>
        </div>
    </div>
    <img src="" alt="" id="img">

    <script>
        var upload = document.querySelector('#submit')
        upload.addEventListener('click', function () {
            var files = document.querySelector('#file').files
            if(files.length<= 0) return alert('请选择文件')
            var fd = new FormData()
            fd.append('avatar', files[0])
            var xhr = new XMLHttpRequest()
            xhr.upload.onprogress = function (e) {
                //  e.lengthComputable 是一个布尔值 表示当前上传的资源是否具有可计算的长度
                if (e.lengthComputable) {
                    // e.loaded:已传输的字节
                    // e.total:需要传输的字节(总字节)
                    var percentComplate = Math.ceil((e.loaded / e.total) * 100)
                    console.log(percentComplate);//计算出上传 百分比
                    // 动态设置进度条
                    $('#jdt').attr('style', 'width:' + percentComplate + '%').html(percentComplate + '%')
                }
            }
            xhr.upload.onload = function () {
                $('#jdt').removeClass().addClass('progress-bar progress-bar-success')
            }
            xhr.open('POST', 'http://www.liulongbin.top:3006/api/upload/avatar')
            xhr.send(fd)
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    console.log(xhr.responseText);
                    var data = JSON.parse(xhr.responseText)
                    if (data.status !== 200) return alert('上传失败' + data.message)
                    document.querySelector('#img').src = 'http://www.liulongbin.top:3006' + data.url
                }
            }
        })
    </script>
    <script src="/js/jquery-1.11.0.min.js"></script>
</body>

</html>